package com.bw.permission.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.permission.common.AjaxResult;
import com.bw.permission.common.BizException;
import com.bw.permission.entity.Role;
import com.bw.permission.service.IRoleMenuService;
import com.bw.permission.service.IRoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2021-08-18
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;


    /**
     * 列表分页查询接口
     * @param role
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("getList")
    public AjaxResult getList(Role role, @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                              @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize) {
        //处理查询条件
        QueryWrapper queryWrapper = new QueryWrapper();
        if (role.getName() != null && !"".equals(role.getName())) {
            queryWrapper.like("name", role.getName());
        }
        if (role.getNameZh() != null && !"".equals(role.getNameZh())) {
            queryWrapper.like("nameZh", role.getNameZh());
        }
        if (role.getCreatedStart() != null) {
            queryWrapper.gt("created", role.getCreatedStart());
        }
        //处理分页
        PageHelper.startPage(pageNo, pageSize);
        List<Role> list = iRoleService.list(queryWrapper);
        PageInfo pageInfo = new PageInfo(list);
        return AjaxResult.ok(pageInfo);
    }

    @GetMapping("getAll")
    public AjaxResult getAll() {
        return AjaxResult.ok(iRoleService.list());
    }

    /**
     * 保存接口（新增、修改）
     * @param role
     * @return
     */
    @PostMapping("save")
    public AjaxResult save(@RequestBody Role role) {
        if (role.getName() == null) {
            throw new BizException(400, "角色名称不能为空");
        }
        if (role.getNameZh() == null) {
            throw new BizException(400, "角色编码不能为空");
        }
        //设置创建时间
        if (role.getId() == null) {
            role.setCreated(LocalDateTime.now());
        }
        iRoleService.saveOrUpdate(role);
        return AjaxResult.ok();
    }

    /**
     * 删除接口
     * @param role
     * @return
     */
    @PostMapping("del")
    public AjaxResult del(@RequestBody Role role) {
        List<Integer> ids = role.getIds();
        if (ids != null && ids.size() > 0) {
            iRoleService.removeByIds(role.getIds());
        }
        return AjaxResult.ok();
    }

}
